//使用ffmpeg命令将视频转成一帧帧的图片
//ffmpeg -i Demo2020_short_1080p-ff4.5.mp4 image-%d.jpeg

#include <stdio.h>	// sprintf fopen printf
#include <malloc.h>	// malloc free

#define MAX_LEN	256

// 将许多JPEG图片合成类似与MJPEG的图片流视频，只是加入了长度和4字节对齐
int main ()
{
	char nstr[MAX_LEN];
	char oname[] = "out.mjpegzj";
	FILE *fpi;
	FILE *fpo;
	int start_code = 0xAABBCCDD;
	int end_code = 0x00000000;

	fpo = fopen(oname, "wb+");
	if (fpo == NULL) {
		printf("Create file %s fail!\n", oname);
		return 0;
	}

	for (int i = 1; i <= 1500; i++)
	{
		sprintf(nstr, "image-%d.jpeg", i);
		fpi = fopen(nstr, "rb");
		if (fpi == NULL) {
			printf("Open file %s fail!\n", nstr);
			break;
		}
		
		fseek(fpi, 0, SEEK_END);
		int flen = ftell(fpi);
		fseek(fpi, 0, SEEK_SET);

		char *pdata = malloc(flen + 4);
		if (pdata == NULL)
		{
			printf("Malloc %d fail!\n", flen);
			break;
		}
		fread(pdata, 1, flen, fpi);
		fclose(fpi);
		
		// 间隔jpeg图片时，先放4字节0xAABBCCDD标志头
		fwrite(&start_code, 4, 1, fpo);
		// 再写4字节jpeg图片长度
		fwrite(&flen, 4, 1, fpo);
		// 写图片数据
		fwrite(pdata, 1, flen, fpo);
		if (flen % 4) {
			printf("file %d, align4: %d\n", i, 4 - flen % 4);
			// 如果图片数据不是4字节对齐的，则用0x00补齐剩下的字节
			fwrite(&end_code, 4 - flen % 4, 1, fpo);
		}
		free(pdata);
	}
	fclose(fpo);

	return 0;
}